<script lang="ts" setup>
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { insertJob, updateJob } from '#/api';
import { ref } from 'vue';
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      componentProps: {
        placeholder: '请输入名称',
      },
      label: '任务名称',
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'description',
      componentProps: {
        placeholder: '请输入描述',
      },
      label: '任务描述',
    },
    {
      component: 'Input',
      fieldName: 'push_content',
      componentProps: {
        placeholder: '请输入推送内容',
      },
      label: '推送内容',
    },
    {
      component: 'Input',
      fieldName: 'cron_expression',
      componentProps: {
        placeholder: '请输入CRON表达式',
      },
      label: 'CRON表达式',
      rules: 'required',
    },
    {
      component: 'Switch',
      defaultValue: true,
      componentProps: {
        class: 'w-auto',
      },
      fieldName: 'push_status',
      label: '是否推送',
    },
  ],
  wrapperClass: 'grid-cols-1',
});
const jobId = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/2',
  onConfirm: submit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      formApi.resetForm();
      const r = drawerApi.getData();
      r['push_status'] = r['push_status'] ? true : false;
      jobId.value = r.id;
      formApi.setValues(r);
    }
  },
});
async function submit() {
  const validate = await formApi.validate();
  if (validate?.valid) {
    const data = await formApi.getValues();
    data['push_status'] = data['push_status'] ? 1 : 0;
    if (jobId.value) {
      updateJob({ ...data, id: jobId.value }).then((r) => {
        drawerApi.close();
      });
    } else {
      insertJob(data).then((r) => {
        drawerApi.close();
      });
    }
  }
}
</script>
<template>
  <Drawer @onConfirm="submit">
    <template #title>
      {{ jobId ? '编辑' : '新增' }}
    </template>
    <BaseForm />
  </Drawer>
</template>
